import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MathTest extends HttpServlet {
    int			x = 3, y = 5, result;
    PrintWriter 	out = null;

    public void doGet( HttpServletRequest req, HttpServletResponse res ) 
	throws ServletException, IOException {
	out = res.getWriter();
	res.setContentType("text/html");
	makeHeader();
	makeQuestion( );
	postQuestion("Try the following question:" );
	makeTail();
	out.close();
    }

    public void doPost ( HttpServletRequest req, HttpServletResponse res ) 
	throws ServletException, IOException {
	out = res.getWriter();
	res.setContentType("text/html");
	result = Integer.parseInt(req.getParameter("result"));
	makeHeader();
	postResponse();
	makeTail();
	out.close();
    }

    void makeQuestion() {
	x = ( int ) ( Math.random() * 100 );
	y = ( int ) ( Math.random() * 100 );
    }

    void makeHeader() {
	out.println("<html><title>Simple Math Test</title><body>");
	out.println("<form name=mathTest action=MathTest method=POST>");
	out.println("<center>");
    }

    void makeTail() {
	out.println("</form></body></html>");
    }


    public void postQuestion( String prompt ) {
	
	out.println("<h1>" + prompt + "<h1><br>");
	out.println("<font color=blue size=+4>");
	out.println( x + " + " + y + " = <input type=text name='result' height=10 size=8>");
	out.println("</font>");
	out.println("<br><br><input type=submit value=Check>");
    }

    boolean checkResult() { return result == x + y ; }

    void postResponse () {
	String prompt = null, clr = null, ans = null; 
	if ( checkResult() ) {	
		prompt = "Here is a new question:";
		clr = "green";
		ans = x + " + " + y + " = " + result + ", is right.";
		makeQuestion();
	} else {
		prompt = "Here is the last question again:";
		clr = "red";
		ans = x + " + " + y + " = " + result + ", is incorrect.";
	}
	out.println("<font size=+1 color=" + clr + ">");
	out.println("<br>Your answer to last question, " + ans); 
	out.println("</font>");
	out.println("<br><br><br>");
	postQuestion(prompt);
   }
}

